package com.example.apigateway.dao;

import com.example.apigateway.common.RestResponse;
import com.example.apigateway.config.GenericRest;
import com.example.apigateway.model.Agency;
import com.example.apigateway.model.User;
import com.example.apigateway.utils.Rests;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2018-06-04
 **/
@Repository
@DefaultProperties(groupKey="userDao",
        commandProperties={@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="2000")},
        threadPoolProperties={@HystrixProperty(name="coreSize",value="10")
                ,@HystrixProperty(name="maxQueueSize",value="1000")},
        threadPoolKey="userDao"
)
public class UserDao {

    @Autowired
    private GenericRest rest;

    private static final Logger logger = LoggerFactory.getLogger(UserDao.class);

    @Value("${user.service.name}")
    private String userServiceName;

    @HystrixCommand(fallbackMethod = "getusernameFb")
    public String  getusername(Long id) {
        String url = "http://user/user/getusername?id=" +id;
        RestResponse<String> restResponse = rest.get(url, new ParameterizedTypeReference<RestResponse<String>>() {
        }).getBody();
        return restResponse.getResult();
    }

    public String getusernameFb(Long id) {
        return "failure";
    }



    public List<User> getUserList(User query) {
        ResponseEntity<RestResponse<List<User>>> resultEntity = rest.post("http://" + userServiceName + "/user/getList", query, new ParameterizedTypeReference<RestResponse<List<User>>>(){});
        RestResponse<List<User>> restResponse = resultEntity.getBody();
        if(restResponse.getCode() == 0) {
            return restResponse.getResult();
        } else {
            return null;
        }
    }


    public List<Agency> getAllAgency() {
        return Rests.exc(()->{
            String url = Rests.toUrl(userServiceName, "/agency/list");
            ResponseEntity<RestResponse<List<Agency>>> responseEntity =
                    rest.get(url, new ParameterizedTypeReference<RestResponse<List<Agency>>>() {});
            return responseEntity.getBody();
        }).getResult();
    }


    public User addUser(User account) {
        String url = "http://" +userServiceName+"/user/add";
        ResponseEntity<RestResponse<User>> responseEntity = rest.post(url, account, new ParameterizedTypeReference<RestResponse<User>>() {});
        RestResponse<User> response = responseEntity.getBody();
        if(response.getCode() == 0) {
            return response.getResult();
        } else {
            throw new IllegalStateException("Can not add user");
        }
    }

    public boolean enable(String key) {
        Rests.exc(()->{
            String url = Rests.toUrl(userServiceName,"/user/enable?key="+key);
            ResponseEntity<RestResponse<Object>> responseEntity =
                    rest.get(url, new ParameterizedTypeReference<RestResponse<Object>>() {});
            return responseEntity.getBody();
        });
        return true;
    }



    public User authUser(User user) {
        String url = "http://" + userServiceName + "/user/auth";
        ResponseEntity<RestResponse<User>>  responseEntity = rest.post(url, user, new ParameterizedTypeReference<RestResponse<User>>() {});
        RestResponse<User> response = responseEntity.getBody();
        if(response.getCode() == 0) {
            return response.getResult();
        } else {
            throw new IllegalStateException("Can not auth user");
        }
    }

    public void logout(String token) {
        String url = "http://" + userServiceName + "/user/logout?token="+ token;
        rest.get(url, new ParameterizedTypeReference<Object>() {});
    }

    /**
     * 调用鉴权服务
     * @param token
     * @return
     */
    public User getUserByToken(String token) {
        String url = "http://" +userServiceName +"/user/get? token="+token;
        ResponseEntity<RestResponse<User>> responseEntity = rest.get(url, new ParameterizedTypeReference<RestResponse<User>>() {});
        RestResponse<User> response = responseEntity.getBody();
        if (response == null || response.getCode()!=0) {
            return  null;
        }
        return response.getResult();
    }



}




